package com.thinkgem.jeesite.modules.erp.web;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.erp.entity.Compare;
import com.thinkgem.jeesite.modules.erp.entity.Goods;
import com.thinkgem.jeesite.modules.erp.entity.GoodsType;
import com.thinkgem.jeesite.modules.erp.entity.MaterialType;
import com.thinkgem.jeesite.modules.erp.entity.Order;
import com.thinkgem.jeesite.modules.erp.entity.OutAndInWarehouseOrder;
import com.thinkgem.jeesite.modules.erp.entity.Page;
import com.thinkgem.jeesite.modules.erp.service.GoodsTypeService;

/**
 * 物品
 * @author lx
 */
@Controller
@RequestMapping(value = "${adminPath}/erp/goodsType")
public class GoodsTypeController extends BaseController {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private GoodsTypeService goodsTypeService;
	
	/**
	 * 查询物品种类树形
	 * @return
	 * @throws JsonProcessingException 
	 */
	@ResponseBody
	@RequestMapping(value = "treeData")
	public String queryGoogsTypeTree(HttpServletRequest request) throws JsonProcessingException{
		String id = request.getParameter("id");
		Map<String,Object>map=new HashMap<String,Object>();
		if(null!=id&&!"".equals(id)){
			String[] sid = id.split("-");
			map.put("fatherGrade", Integer.parseInt(sid[1])+1);
			map.put("fatherCode", sid[0]);
			map.put("sonGrade", Integer.parseInt(sid[1])+2);
		}else{
			map.put("fatherGrade", 1);
			map.put("sonGrade", 2);
		}
		List<GoodsType>list=goodsTypeService.queryGoodsTree(map);
		
		ObjectMapper om = new ObjectMapper ();
		String depstr = om.writeValueAsString (list);
		return depstr;
	}
	//返回右边页面
	@RequestMapping(value = "toQueryGoods")
	public String toQueryGoods(HttpServletRequest request,Model model) throws JsonProcessingException{
		String typeId = request.getParameter("typeId");
		if(null==typeId){
			return "modules/erp/empty";
		}else{
			model.addAttribute("typeId", typeId);
			return "modules/erp/goodsStatistics";
		}
	}
	
	//异步返回具体物品---抛弃
	@ResponseBody
	@RequestMapping(value = "queryLinkGoods")
	public String queryLinkGoods(HttpServletRequest request) throws JsonProcessingException{
		String typeId = request.getParameter("typeId");//编号-等级
		String sonTypeId = request.getParameter("sonTypeId");
		GoodsType g=null;
		List<GoodsType> gl=null;
		String depstr=null;
		ObjectMapper om = new ObjectMapper ();
		if(null!=typeId&&!"".equals(typeId)){
			g=goodsTypeService.queryLinkGoods(typeId);
			depstr = om.writeValueAsString (g);
			if(null!=depstr&&!"".equals(depstr)&&!"[]".equals(depstr)){
				depstr = "["+depstr.replaceAll("list", "children").replaceAll("\"state\":null,", "")+"]";
			}
		}else{
			gl=goodsTypeService.queryLinkGoodsOt(sonTypeId);
			depstr = om.writeValueAsString (gl);
			if(null!=depstr&&!"".equals(depstr)&&!"[]".equals(depstr)){
				depstr = depstr.replaceAll("list", "children").replaceAll("\"state\":null,", "");
			}
		}
		return depstr;
	}
	
	//异步模糊返回物品
	@ResponseBody
	@RequestMapping(value = "dimQueryLinkGoods")
	public String dimQueryLinkGoods(HttpServletRequest request) throws JsonProcessingException{
		String cssb = request.getParameter("cssb");//物品类别：编号-等级	3-1
		String key = request.getParameter("key");//关键字
		List<Goods>list=null;
		if(null==key||"".equals(key)){
			return null;
		}else{
			Map<String,Object>map=new HashMap<String,Object>();
			String[] split = cssb.split("-");
			map.put("start", split[0]);
			map.put("key", key);
			key = key.trim();
            String[] nameSp = key.split(" ");
            if(nameSp.length>1){
                List<String> strings = Arrays.asList(nameSp);
                list=goodsTypeService.dimQueryLinkGoodsByNames(strings);
            }else{
                list=goodsTypeService.dimQueryLinkGoods(map);
            }

		}
		ObjectMapper om = new ObjectMapper ();
		String depstr = om.writeValueAsString (list);
		if(null!=depstr&&!"".equals(depstr)){
			depstr=depstr.replaceAll("code", "gid").replaceAll("name", "gname").replaceAll("type", "series");
		}
		return depstr;
	}
	
	
	@ResponseBody
	@RequestMapping(value = "goodsStatistics")
	public String goodsStatistics(OutAndInWarehouseOrder order) throws JsonProcessingException{
		String list=goodsTypeService.goodsStatistics(order);
		return list;
	}
	
	//物件剩余查询
	@RequestMapping(value={"queryResidue"})
	public String queryResidue(HttpServletRequest request,Model model) throws JsonProcessingException{
		String typeId = request.getParameter("typeId");
		List<Goods>list=null;
		if(null==typeId){
			return "modules/erp/empty";
		}else{
			String[] split = typeId.split("-");
			Map<String,Object>map=new HashMap<String,Object>();
			map.put("start",split[0]);
			list=goodsTypeService.queryResidue(map);
			ObjectMapper om = new ObjectMapper ();
			String depstr = om.writeValueAsString (list);
			model.addAttribute("par", typeId);
			model.addAttribute("list", depstr);
			return "modules/erp/queryResidue";
		}
	}
	
	//异步查询剩余
	@RequestMapping(value={"ajQueryResidue"})
	@ResponseBody
	public String ajQueryResidue(HttpServletRequest request,Model model) throws JsonProcessingException{
		ObjectMapper om = new ObjectMapper ();
		String wellNo = request.getParameter("WellNo");
		String page = request.getParameter("page");
		String pageSize = request.getParameter("pageSize");
		String[] split = null;
		Map<String,Object>map=new HashMap<String,Object>();
		map.put("start", (Integer.parseInt(page)-1)*(Integer.parseInt(pageSize)));
		map.put("pageSize", pageSize);
		Page<Goods> gPage = new Page<Goods>();
		if(wellNo != null && wellNo.contains("-")){
			split = wellNo.split("-");
			map.put("wellNo", split[0]);
			//查询出总数和当前需要的数据
			gPage=goodsTypeService.ajQueryResidue(map);
		}else{

			if(wellNo != null){
				split = wellNo.split(" ");
				List<String> strings = Arrays.asList(split);
				map.put("wellNo", strings);
			}

			//查询出总数和当前需要的数据
			 gPage=goodsTypeService.ajQueryResidueParameter(map);
		}

		
		String depstr = om.writeValueAsString (gPage);
		return depstr;
	}
	
	//根据物料编号删除物料
	@RequestMapping(value={"deleteGoods"})
	public String deleteGoods(HttpServletRequest request,Model model) throws JsonProcessingException{
		String goodsCode = request.getParameter("goodsCode");
		String wellNo = request.getParameter("wellNo");
		goodsTypeService.deleteGoods(goodsCode);
		return "redirect:"+Global.getAdminPath()+"/erp/goodsType/queryResidue?typeId="+wellNo;
	}
	
	//新增物料(异步校验物料编号或名称是否重复)
	@RequestMapping(value={"saveGoods"})
	@ResponseBody
	public String saveGoods(Goods goods,Model model) throws JsonProcessingException{
		String result=goodsTypeService.saveGoods(goods);//校验，保存
		return result;
	}
	
	//修改物件
	@RequestMapping(value={"updateGoods"})
	@ResponseBody
	public String updateGoods(Goods goods,Model model) throws JsonProcessingException{
		String result=goodsTypeService.updateGoods(goods);//校验，修改
		return result;
	}
	
	
	//物料类型管理
	@RequestMapping(value={"materialManage"})
	public String materialManage(HttpServletRequest request,Model model){
		String typeId = request.getParameter("typeId");
		String typeName = request.getParameter("typeName");
		String parentId = request.getParameter("parentId");
		if(null!=typeId){
			model.addAttribute("typeId", typeId);
			model.addAttribute("typeName", typeName);
			model.addAttribute("parentId", parentId);
			return "modules/erp/materialManageRight";
		}else{
			return "modules/erp/materialManage";
		}
	}
	
	//校验新增物料类型
	@RequestMapping(value={"addMaterial"})
	@ResponseBody
	public String addMaterial(MaterialType type,Model model){
		if(null==type.getcInvCCode()||null==type.getcInvCName()){
			return "0";
		}
		String result=goodsTypeService.addMaterial(type);//校验，新增
		return result;
	}
	
	//校验修改物料类型
	@RequestMapping(value={"updateMaterial"})
	@ResponseBody
	public String updateMaterial(MaterialType type,Model model){
		if(null==type.getcInvCCode()||null==type.getcInvCName()){
			return "0";
		}
		String result=goodsTypeService.updateMaterial(type);//校验，修改
		return result;
	}
	
	
	//去查询原erp系统的物料
	@RequestMapping(value={"queryParentMaterial"})
	public String queryParentMaterial(){
		return "modules/erp/toQueryParentMaterial";
	}
	
	@ResponseBody
	@RequestMapping(value = "parentTreeData")
	public String parentQueryGoogsTypeTree(HttpServletRequest request) throws Exception{
		String id = request.getParameter("id");
		Map<String,Object>map=new HashMap<String,Object>();
		
		if(null!=id&&!"".equals(id)){
			String[] sid = id.split("-");
			map.put("fatherGrade", Integer.parseInt(sid[1])+1);
			map.put("fatherCode", sid[0]);
			map.put("sonGrade", Integer.parseInt(sid[1])+2);
			
		}else{
			map.put("fatherGrade", 1);
			map.put("sonGrade", 2);
		}
		List<GoodsType>list=goodsTypeService.parentQueryGoodsTree(map);
		ObjectMapper om = new ObjectMapper ();
		String depstr = om.writeValueAsString (list);
		return depstr;
	}
	
	
	//物件剩余查询，sqlserver数据库
	@RequestMapping(value={"queryParentResidue"})
	public String queryParentResidue(HttpServletRequest request,Model model) throws Exception{
		String typeId = request.getParameter("typeId");
		List<Goods>list=null;
		if(null==typeId){
			return "modules/erp/empty";
		}else{
			String[] split = typeId.split("-");
			Map<String,Object>map=new HashMap<String,Object>();
			map.put("start",split[0]);
			list=goodsTypeService.queryParentResidue(map);
			ObjectMapper om = new ObjectMapper ();
			String depstr = om.writeValueAsString (list);
			model.addAttribute("par", typeId);
			model.addAttribute("list", depstr);
			return "modules/erp/queryParentResidue";
		}
	}
	
	//异步查询剩余
	@RequestMapping(value={"ajQueryParentResidue"})
	@ResponseBody
	public String ajQueryParentResidue(HttpServletRequest request,Model model) throws Exception{
		ObjectMapper om = new ObjectMapper ();
		String wellNo = request.getParameter("WellNo");
		String page = request.getParameter("page");
		String pageSize = request.getParameter("pageSize");
		String[] split = wellNo.split("-");
		Map<String,Object>map=new HashMap<String,Object>();
		map.put("wellNo", split[0]);
		map.put("start", (Integer.parseInt(page)-1)*(Integer.parseInt(pageSize)));
		map.put("pageSize", pageSize);
		//查询出总数和当前需要的数据
		Page<Goods> gPage=goodsTypeService.ajQueryParentResidue(map);
		
		String depstr = om.writeValueAsString (gPage);
		return depstr;
	}
	
	//异步模糊返回物品
	@ResponseBody
	@RequestMapping(value = "dimQueryParentLinkGoods")
	public String dimQueryParentLinkGoods(HttpServletRequest request) throws Exception{
		String cssb = request.getParameter("cssb");//物品类别：编号-等级	3-1
		String key = request.getParameter("key");//关键字
		List<Goods>list=null;
		if(null==key||"".equals(key)){
			return null;
		}else{
			Map<String,Object>map=new HashMap<String,Object>();
			String[] split = cssb.split("-");
			map.put("start", split[0]);
			map.put("key", key);
			list=goodsTypeService.dimQueryParentLinkGoods(map);
		}
		ObjectMapper om = new ObjectMapper ();
		String depstr = om.writeValueAsString (list);
		if(null!=depstr&&!"".equals(depstr)){
			depstr=depstr.replaceAll("code", "gid").replaceAll("name", "gname").replaceAll("type", "series");
		}
		return depstr;
	}
	
	//更新类目
	@ResponseBody
	@RequestMapping(value = "updateClass")
	public String updateClass() throws Exception{
		List<Map<String,Object>> list=goodsTypeService.queryAllClass();
		String result=null;
		if(list.size()!=0){
			try {
				goodsTypeService.updateClass(list);
				result="1";
			} catch (Exception e) {
				e.printStackTrace();
				result="0";
			}
		}
		return result;
	}
	
	//更新所有物料
	@ResponseBody
	@RequestMapping(value = "updateInventory")
	public String updateInventory() throws Exception{
		String result=null;
		try {
			List<Map<String,Object>> insertList=goodsTypeService.queryInsert();//需要新增的
			List<String> deleteList=goodsTypeService.queryDelete();//需要删除的
			List<Compare> updateList=goodsTypeService.queryUpdate();//修改修改的
			//更新
//			goodsTypeService.updateInventory2(insertList);
			goodsTypeService.updateInventory(insertList,deleteList,updateList);
			result="1";
		} catch (Exception e) {
			e.printStackTrace();
			result="0";
		}
		
		return result;
	}
	
	//分页查询订单详情
	@RequestMapping(value="queryOrdersInfo")
	@ResponseBody
	public String queryOrdersInfo(Order order) throws JsonProcessingException{
		order.setPageNumber((order.getPageNumber()-1)*order.getPageSize());
		//根据参数返回分页数据
		Page<OutAndInWarehouseOrder> page=goodsTypeService.queryOrdersInfo(order);
		ObjectMapper om = new ObjectMapper ();
		String depstr = om.writeValueAsString (page);
		if(null!=depstr){
			depstr=depstr.replaceAll("code", "oCode").replaceAll("executor", "executorCode").replaceAll("time", "execDate").replaceAll("type", "oType")
					.replaceAll("status", "oStatus");
		}
		return depstr;
	}
	
}
